/*
 * @Author: Gavin
 * @Date: 2018-09-07 09:44:06
 * @LastEditors: Gavin
 * @LastEditTime: 2018-09-07 16:33:11
 * @Description:
 */
import Koa from 'koa'
import config from '../config'
import chalk from 'chalk'
import compress from 'koa-compress'

import ssrMiddleware from './middleware/ssrMiddleware'
import renderMiddleware from './middleware/renderMiddleware'
import storeMiddleware from './middleware/storeMiddleware'
import logMiddleware from './middleware/logMiddleware'

// 创建koa服务器应用
const app = new Koa()

const Listen = () => {
    const server = app.listen(config.serverPort, (err) => {
        if (err) {
            console.error(chalk.yellow(`==> 😭  OMG!!! ${err}`))
        }
        const host = server.address().address
        console.info(chalk.green(`==> 🌎  Listening at http://${host}:${config.serverPort}`))

    })
    return server
}

export const createApp = () => {
    // app.use(logMiddleware())
    // app.use(compress())
    return app
}

// 配置及初始化Koa服务器
export const creatServer = () => {
    app.use(renderMiddleware())
    app.use(storeMiddleware())
    app.use(ssrMiddleware())
    return Listen()
}
